import React, { useState, useEffect } from 'react';
import { Button, Form } from 'antd';
import moment from 'moment';

import { SearchInput } from '@/components/UserForm';
import { isSuccess } from '@/utils/request';
import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';

import { NumberSettingInput } from '@/pages/SalaryManage/components/NumberSettingInput';
import { numberFormat } from '@/utils/formatterUtil';
import EditTable from './EditTable';

const ValidatorTable = ({ value, onChange, isApply, user, employeeList = [], decimalPlaces = 1 }) => {
    const [dataSource, setDataSource] = useState(value);
    const [columns, setColumns] = useState([]);

    // 添加
    const handleAdd = () => {
        const newData = {
            employeeCode: undefined,
            employeeNo: '',
            employeeName: '',
            departmentName: '',
            departmentCode: '',
            amt: null,
            isValidatorPass: false,
            id: moment() + Math.ceil(Math.random() * 1000).toString()
        };
        setDataSource([...dataSource, newData]);
    };

    // 编辑行变化保存
    const handleRowSave = row => {
        const newData = dataSource;
        const index = newData.findIndex(item => row.id === item.id);
        const item = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row
        });
        setDataSource([...newData]);
    };

    // 删除
    const handleDelete = record => {
        const arr = dataSource.filter(item => item.id !== record.id);
        setDataSource([...arr]);
    };

    // 改变表单数据
    const changeTableVal = (id, key, val) => {
        console.log(id, key, val);
        const employeesList = dataSource;
        employeesList.map(child => {
            if (child.id === id) {
                child[key] = val;
                if (key === 'employeeCode') {
                    const employee = employeeList.filter(it => it.employeeCode === val);
                    child.employeeName = employee[0]?.name;
                    child.employeeNo = employee[0]?.employeeNo;
                    child.departmentCode = employee[0]?.departmentCode;
                    child.departmentName = employee[0]?.departmentName;
                }
            }
            return child;
        });
        setDataSource(employeesList);
    };

    useEffect(() => {
        const tempColumns = [
            {
                title: '发薪对象',
                dataIndex: isApply ? 'employeeCode' : 'employeeName',
                width: '25%',
                editable: true,
                rules: [
                    {
                        required: true,
                        message: '发薪对象不能为空！'
                    }
                ],
                editrender: ({ record, save, form, dataIndex, title }) => (
                    <>
                        <Form.Item
                            style={{
                                margin: 0
                            }}
                        >
                            {form.getFieldDecorator(dataIndex, {
                                rules: [
                                    {
                                        required: true,
                                        message: `${title}必选`
                                    }
                                ],
                                initialValue: record[dataIndex] || undefined
                            })(
                                <SearchInput
                                    getData={async () => {
                                        if (employeeList.length > 0) {
                                            return employeeList;
                                        }
                                        const employeeResponse = isApply ? await queryEmployeeList({
                                            organizationCode: user?.companyId
                                        }) : null;
                                        const data = isSuccess(employeeResponse) ? employeeResponse.data : [];
                                        return data;
                                    }}
                                    selectProps={{
                                        placeholder: '请选择发薪对象',
                                        allowClear: false,
                                        disabled: !isApply,
                                        onPressEnter: save,
                                        onBlur: save
                                    }}
                                    fieldsName={{
                                        value: 'employeeCode',
                                        title: 'name'
                                    }}
                                    onChange={val => changeTableVal(record.id, 'employeeCode', val)}
                                />
                            )}
                        </Form.Item>
                    </>
                ),
                render: (text, record) => record.employeeName
            },
            {
                title: '所属部门',
                dataIndex: 'departmentName',
                width: '30%'
            },
            {
                title: '发薪金额',
                dataIndex: 'amt',
                width: '25%',
                editable: true,
                rules: [
                    {
                        required: true,
                        message: '发薪金额不能为空！'
                    }
                ],
                editrender: ({ record, save, form: columnForm, dataIndex, title }) => (
                    <>
                        <Form.Item
                            style={{
                                margin: 0
                            }}
                        >
                            {columnForm.getFieldDecorator(dataIndex, {
                                rules: [
                                    {
                                        required: true,
                                        message: `${title}必填`
                                    }
                                ],
                                initialValue: record[dataIndex] || undefined
                            })(
                                <NumberSettingInput
                                    placeholder="请输入金额"
                                    disabled={!isApply}
                                    onPressEnter={save}
                                    onBlur={save}
                                    thousandsSeparator=","
                                    maxLength={20}
                                />
                            )}
                        </Form.Item>
                    </>
                ),
                align: 'right',
                render: text => numberFormat(text, decimalPlaces)
            },
            {
                title: '操作',
                width: '20%',
                hidden: !isApply,
                align: 'center',
                render(t, record) {
                    return (
                        <Button disabled={!isApply} onClick={() => handleDelete(record)}>
                            -
                        </Button>
                    );
                }
            }
        ];
        setColumns([...tempColumns]);
    }, [dataSource, value, employeeList]);

    useEffect(() => {
        if (value && onChange) {
            onChange(dataSource);
        }
    }, [dataSource]);

    return (
        <div>
            <EditTable bordered dataSource={dataSource} columns={columns} handleRowSave={handleRowSave} rowKey="id" />
            {isApply === true && (
                <Button
                    type="dashed"
                    onClick={handleAdd}
                    block
                    style={{
                        marginTop: 16
                    }}
                >
                    <span
                        style={{
                            fontSize: 18,
                            marginRight: 3
                        }}
                    >
                        +
                    </span>{' '}
                    添加
                </Button>
            )}
        </div>
    );
};

export default React.forwardRef(ValidatorTable);
